package com.aiwhose.aiwhosewechatplublicaiwhose.utils;/**
 * /**
 *
 * @program: aiwhose_service
 * @description: 微信公众号工具类
 * @author: 田国刚
 * @create: 2024-02-18 14:09
 **/

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.CustomMessageBean;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.ReceiveMessageBean;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.ReplyMessageBean;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.WXPlublicUserInfoBean;
import com.aiwhose.aiwhosewechatplublicaiwhose.service.UserService;
import com.aiwhose.aiwhosewechatplublicaiwhose.service.XunFeiBigModelService;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.message.WXMessageCustomerUtil;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.message.WXMessageOrdinaryUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WXPlublicUtil {
    private static final Logger log = LoggerFactory.getLogger(WXPlublicUtil.class);
    @Resource
    public RedisUtil redisUtil;

    @Resource
    WXEventUtil wxEventUtil;
    @Resource
    UserService userService;
    @Resource
    WXMessageOrdinaryUtil wxMessageOrdinaryUtil;
    @Resource
    WXMessageCustomerUtil wxMessageCustomerUtil;
    @Resource
    XunFeiBigModelService xunFeiBigModelService;

    @Value("${wechat_public.grant_type}")
    public String grantType;
    @Value("${wechat_public.secret}")
    public String secret;
    @Value("${wechat_public.appid}")
    public String appid;
    @Value("${wechat_public.token}")
    public String token;


    public String getAccessToken() {
        String wXPlublicAccessToken = (String) redisUtil.get("system:aiwhosePlublic:ACCESSTOKEN");
        if (StrUtil.isNotBlank(wXPlublicAccessToken)) {
            return wXPlublicAccessToken;
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type", grantType);
        map.put("secret", secret);
        map.put("appid", appid);

        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", map);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        String accessToken = jsonObject.getStr("access_token");
        if (StrUtil.isNotBlank(accessToken)) {
            redisUtil.set("system:aiwhosePlublic:ACCESSTOKEN", jsonObject.get("access_token"), 7150);
        }
        return jsonObject.getStr("access_token");
    }


    // 以下是处理不同类型消息的方法，你需要根据实际情况编写这些方法

    public String handleTextMessage(Map<String, Object> xml) throws   IOException {

        ReceiveMessageBean.TextMessage textMessage = BeanUtil.toBean(xml, ReceiveMessageBean.TextMessage.class);
//        讯飞大模型
        String returnMessage = xunFeiBigModelService.getAnswer(textMessage.getFromUserName(), textMessage.getContent());

        log.error("xunfei:{}", returnMessage);
        ReplyMessageBean.TextReplyMessage textReplyMessage = BeanUtil.toBean(textMessage, ReplyMessageBean.TextReplyMessage.class);
        textReplyMessage.setContent(returnMessage);

        if (returnMessage.length() > 2048) {
            log.error("长文本");
            List<String> parts = splitStringByLength(returnMessage, 2048 / 3);
            for (String part : parts) {
                CustomMessageBean.TextMessage customTextMessage = new CustomMessageBean.TextMessage(textMessage.getFromUserName(), part);
                wxMessageCustomerUtil.sendTextMessage(customTextMessage);
            }
            wxMessageCustomerUtil.InputState(textMessage.getFromUserName(), "CancelTyping");
        }

        log.error("短文本");
        return wxMessageOrdinaryUtil.createReturnTextMessage(textReplyMessage);
    }

    public String handleImageMessage(Map<String, Object> xml) {
        // 处理图片消息逻辑


        return null;
    }

    public String handleVoiceMessage(Map<String, Object> xml) {
        // 处理语音消息逻辑
        return null;
    }

    public String handleVideoMessage(Map<String, Object> xml) {
        // 处理视频消息逻辑
        return null;
    }

    public String handleShortVideoMessage(Map<String, Object> xml) {
        // 处理短视频消息逻辑
        return null;
    }

    public String handleLocationMessage(Map<String, Object> xml) {
        // 处理地理位置消息逻辑
        return null;
    }

    public String handleLinkMessage(Map<String, Object> xml) {
        // 处理链接消息逻辑
        return null;
    }

    public String handleEventMessage(Map<String, Object> xml) throws JsonProcessingException {
        ReceiveMessageBean.EventMessage eventMessage = BeanUtil.toBean(xml, ReceiveMessageBean.EventMessage.class);
        switch (eventMessage.getEvent()) {
            case "subscribe":
                // 处理订阅事件逻辑
                WXPlublicUserInfoBean wxPlublicUserInfoBean = wxEventUtil.subscribeEvent(eventMessage);
                boolean b = userService.saveUserByPlublic(wxPlublicUserInfoBean);
                ReplyMessageBean.TextReplyMessage textReplyMessage = BeanUtil.toBean(eventMessage, ReplyMessageBean.TextReplyMessage.class);
                textReplyMessage.setContent("欢迎使用“谁的人工智能”，有任何帮助请微信联系：aiwhose ，我们将全程为您服务！");

                return wxMessageOrdinaryUtil.createReturnTextMessage(textReplyMessage);
            case "unsubscribe":
                // 处理取消订阅事件逻辑
                return null;
            case "CLICK":
                // 处理点击菜单拉取消息时的事件推送
                return null;
            case "VIEW":
                // 处理点击菜单跳转链接时的事件推送
                return null;
            case "SCAN":
                // 处理扫码推事件且弹出“消息接收中”提示框的事件推送
                return wxEventUtil.scanEvent(eventMessage);
            case "LOCATION":
                // 处理上报地理位置事件的事件推送
                return null;
            default:
                // 其他事件类型
                return null;
        }

    }

    public static List<String> splitStringByLength(String input, int maxLength) {
        List<String> result = new ArrayList<>();
        int start = 0;
        while (start < input.length()) {
            // Check if the rest of the string is shorter than maxLength
            int end = Math.min(start + maxLength, input.length());
            result.add(input.substring(start, end));
            start = end; // Move start to end for the next substring
        }
        return result;
    }
}
